package com.ruoyi.alarmmanagement.job;

import com.ruoyi.alarmmanagement.entity.TerminalWarn;
import com.ruoyi.alarmmanagement.entity.WarnStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 大用户表流量空值报警
 * @author TsingYu
 * @version 1.0
 * @date 2024/8/16 15:50
 */
@Component("zeroUsageDb")
@Slf4j
public class ZeroUsageDb extends BaseWarnJob{
    /**
     * 获取预警参数类型-大用户表流量空值报警
     *
     * @return 预警参数类型-大用户表流量空值报警
     */
    @Override
    protected  String getWarnParamType() {
        return "11";
    }

    /**
     * 获取预警类型
     *
     * @return 预警类型
     */
    @Override
    protected int getWarnType() {
        return 5;
    }

    /**
     * 执行预警数据生成-大用户表流量空值预警
     *
     * @param date 生成指定日期的预警数据
     */
    @Override
    public void execute(Date date) {
        List<TerminalWarn> terminals = getWarnStrategyMapper().selectZeroUsageDb(date, getWarnParamType(), WarnStrategy.WARN_TARGET_TYPE_DB);
        if (CollectionUtils.isEmpty(terminals)) {
            log.info("无大用户表流量空值预警信息");
            return;
        }
        Map<String, Map<String, Optional<TerminalWarn>>> groupedResult = terminals.stream()
                .collect(Collectors.groupingBy(TerminalWarn::getLocationNb,
                        Collectors.groupingBy(TerminalWarn::getTenantId,
                                Collectors.minBy(Comparator.comparingLong(tw -> Math.abs(tw.getReadTime().getTime() - date.getTime())))
                        )
                ));

        List<TerminalWarn> result = groupedResult.values().stream()
                .flatMap(map -> map.values().stream())
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());

        boolean success = insertWarnBatch(result, getWarnType());
        if (success) {
            log.info(String.format("大用户表流量空值预警数据生成成功，共%d条", result.size()));
        }
    }
}
